package com.biz.primus.support.localhost.spring;


import org.apache.commons.codec.binary.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.PropertySource;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;

/**
 *
 * @author yanweijin
 * @date 2017/11/26
 */

public class LocalhostPropertySource extends PropertySource<Void> {


	private static final Logger log = LoggerFactory.getLogger(LocalhostPropertySource.class);
	private static final String SOURCE_NAME = "primus.localhost";
	private static final String PREFIX = SOURCE_NAME+".";


	public LocalhostPropertySource(String name) {
		super(name);
	}

	public LocalhostPropertySource(){
		this(SOURCE_NAME);
	}

	@Override
	public Object getProperty(String name) {
		if(name.startsWith(PREFIX)){
			try {
				return getPropertyWithKey(name.substring(PREFIX.length()));
			} catch (Exception e) {
				log.error("获取本地主机唯一属性出错,返回默认值",e);
				return "localhost";
			}
		}
		return null;
	}

	private String getPropertyWithKey(String key) throws Exception{
		switch (key) {
			case "mac": return getLocalhostMacAddress();
			case "ip":  return getLocalhostIpAddress();
			default:    throw new IllegalArgumentException("无效的属性key:"+PREFIX+key);
		}
	}

	private String getLocalhostIpAddress() throws UnknownHostException {
		return InetAddress.getLocalHost().getHostAddress();
	}

	private String getLocalhostMacAddress() throws Exception {
		InetAddress host = InetAddress.getLocalHost();
		byte[] hardwareAddress = NetworkInterface.getByInetAddress(host).getHardwareAddress();
		return Hex.encodeHexString(hardwareAddress);
	}


}
